package com.example.helloworld;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

import edu.uci.ics.ics163.gpsdrawupload.Point;
import edu.uci.ics.ics163.gpsdrawupload.StrokeManager;
//import edu.uci.ics.ics163.gpsdrawupload.StrokeManager;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.os.Build;


public class MainActivity extends Activity implements GooglePlayServicesClient.ConnectionCallbacks,
	GooglePlayServicesClient.OnConnectionFailedListener, LocationListener 
{
	
	static LocationClient mLocationClient;
	private String lastLocation;
	private static boolean mLocationClientConnected;
	private static double currentLat = 0;
	private static double currentLong = 0;
	
	private static LocationRequest mLocationRequest;
	
	private int UPDATE_INTERVAL = 5000;
	private int FASTEST_INTERVAL = 1000;
	
	private static int red = 0;
	private static int green = 0;
	private static int blue = 255;
	
	static StrokeManager stkmngr;
	static boolean startCollecting = false;
	static int strokeNum = 0;
	
    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);        
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
        
        mLocationClient = new LocationClient(this, this, this);
        mLocationClient.connect();
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        
        stkmngr = new StrokeManager();
        
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    
    public static class ErrorDialogFragment extends DialogFragment {
    	private Dialog mDialog;
    	
    	public ErrorDialogFragment()
    	{
    		super();
    		mDialog = null;
    	}
    	
    	public void setDialog(Dialog dialog)
    	{
    		mDialog = dialog;
    	}
    	
    	public Dialog onCreateDialog(Bundle savedInstanceState)
    	{
    		return mDialog;
    	}
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment 
    {
    	EditText groupText, picText;
    	Button upDateButton;
		private static TextView locationView, buffer;
		//ToggleButton locBtn;
		private RadioGroup radioGroupId;
		private Button colorBtn;
		private RadioButton colorSelected;
		private Button singlePointButton;

        public PlaceholderFragment() 
        {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) 
        {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            
            locationView = (TextView) rootView.findViewById(R.id.Location);
            buffer = (TextView) rootView.findViewById(R.id.Buffer);
            
            radioGroupId = (RadioGroup) rootView.findViewById(R.id.Color);
    	 
    	    radioGroupId.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() 
    	    {
				public void onCheckedChanged(RadioGroup group, int checkedId) 
				{
					RadioButton pressedButton = (RadioButton) group.findViewById(checkedId);
					if(pressedButton.getText().toString().equals("Red"))
					{
						red = 255;
						green = 0;
						blue = 0;
						
					}
					if(pressedButton.getText().toString().equals("Green"))
					{
						red = 0;
						green = 255;
						blue = 0;
					}
					if(pressedButton.getText().toString().equals("Blue"))
					{
						red = 0;
						green = 0;
						blue = 255;
					}
					
				}
			});
                    
            groupText = (EditText) rootView.findViewById(R.id.GroupName);
            picText = (EditText) rootView.findViewById(R.id.PictureID);
            singlePointButton = (Button) rootView.findViewById(R.id.SinglePoint);
            singlePointButton.setOnClickListener(new View.OnClickListener() 
            {		
				@Override
				public void onClick(View v) 
				{
					long time = System.currentTimeMillis();
					String stroke = "" + strokeNum;
					stkmngr.setStrokeColor(stroke, red, green, blue);
					Point p = new Point(time, currentLat, currentLong);
					stkmngr.addPoint(stroke, p);
					Log.v("DebugMsg", p.getLat() + ", " + p.getLng());
					
				}
			});
            
            
            upDateButton = (Button) rootView.findViewById(R.id.button1);
            upDateButton.setOnClickListener(new View.OnClickListener() 
            {		
				@Override
				public void onClick(View v) 
				{
					dynamicClick(v);
				}
			});
            
            ToggleButton toggle = (ToggleButton) rootView.findViewById(R.id.TogglePen);
            toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() 
            {
                

				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
                {
                	if (isChecked) 
                	{
                		startCollecting = true;
                	}
                	else
                	{
                		//stop storing the data
                		System.out.println("Stop storing data");
                		startCollecting = false;
                		strokeNum++;
                	}
                	
                }   
            });
            
            return rootView;
        }
        
        //Use this function to upload the data to the server
		private void dynamicClick(View v) 
		{
			Log.v("DebugMsg", "Group Name: " + groupText.getText().toString() 
						+ ". Picture ID: " + picText.getText().toString() + 
						"  (" + red +", " + green + ", "+ blue + ")");
			stkmngr.upload(groupText.getText().toString().trim(), picText.getText().toString().trim());
		}
		
    }
    
    private void updateUI()
    {
    	runOnUiThread(new Runnable()
    	{
			@Override
			public void run() 
			{
				if((PlaceholderFragment.locationView != null) && (lastLocation != null) && PlaceholderFragment.buffer != null)
				{
					
					PlaceholderFragment.locationView.setText(lastLocation);
					String s = "" + stkmngr.countPoints();
					PlaceholderFragment.buffer.setText(s);
				}
			}
    	});
    }

	@Override
	public void onConnected(Bundle arg0) 
	{
		Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
		mLocationClientConnected = true;
		//Location mCurrentLocation = mLocationClient.getLastLocation();
		//lastLocation = "(" + mCurrentLocation.getLatitude() + ", " + mCurrentLocation.getLongitude() + ")";
		//updateUI();
		if((mLocationClient != null) && (mLocationClientConnected) && (mLocationRequest != null))
		{
			mLocationClient.requestLocationUpdates(mLocationRequest, this);
		}
		
	}


	@Override
	public void onDisconnected() 
	{
		
		
	}


	@Override
	public void onConnectionFailed(ConnectionResult result) {
		if(result.hasResolution())
		{
			try
			{
				result.startResolutionForResult(this,  CONNECTION_FAILURE_RESOLUTION_REQUEST);
			} catch (IntentSender.SendIntentException e)
			{
				e.printStackTrace();
			}
		}
		else
		{
			Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
						this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
			if(errorDialog != null)
			{
				ErrorDialogFragment errorFragment = new ErrorDialogFragment();
				errorFragment.setDialog(errorDialog);
				errorFragment.show(getFragmentManager(), "Location Updates");
			}
		}
	}
	
	@Override
	public void onLocationChanged(Location location) 
	{
		currentLat = location.getLatitude();
		currentLong = location.getLongitude();
		long time = System.currentTimeMillis();
		String display = "Current Time: " + time + " (" +location.getLatitude() + ", " + location.getLongitude() + ")";
		if(startCollecting)
		{
			String stroke = "" + strokeNum;
			stkmngr.setStrokeColor(stroke, red, green, blue);
			Log.v("DebugMsg", display);
			Point p = new Point(time, location.getLatitude(), location.getLongitude());
			stkmngr.addPoint(stroke, p);
			Log.v("DebugMsg", p.getLat() + ", " + p.getLng());
			
			String s = "" + stkmngr.countPoints();
			Log.v("DebugMsg", s);
			
		}		
		this.lastLocation = display;	
		updateUI();
	}

}
